'use strict';
let BaseController = require('./base.js');

class RoleController extends BaseController {
    async index() {
        let result = await this.ctx.model.Role.find({}).sort({ sort: -1 }) ;
        this.success(200, '获取成功',result)
    }

    async add() {
        const {title,description} = this.ctx.request.body;
        let role = new this.ctx.model.Role({
            title,
            description
        })
        await role.save();
        await this.success(200, '增加角色成功');
    }

    async edit() {

        /*
        { _csrf: 'b6TZ302c-LE44hFJ7LW9q3aBsmWztZXEA3Vw',
        _id: '5b8cecf5ebad41239888d3e9',
        title: '网站编辑111',
        description: '网站编辑222' }
        */
        let {_id, title, description} = this.ctx.query;
        await this.ctx.model.Role.updateOne({"_id": _id}, {
            title, description
        })
        await this.success(200, '修改角色成功');

    }
    async delete(){
        let _id = this.ctx.query._id;
        const result = await this.ctx.model.Role.deleteOne({"_id": _id});
        if (result.deletedCount != 0) {
            this.success(200, '删除用户信息成功')
        } else {
            this.error(303, '删除用户信息失败')
        }
    }

    async auth() {
        let role_id = this.ctx.request.body.role_id;
        let access_node = this.ctx.request.body.access_node;
        //1、删除当前角色下面的所有权限
        await this.ctx.model.RoleAccess.deleteMany({"role_id": role_id});
        //2、给role_access增加数据 把获取的权限和角色增加到数据库
        for (let i = 0; i < access_node.length; i++) {
            let roleAccessData = new this.ctx.model.RoleAccess({
                role_id: role_id,
                access_id: access_node[i]
            })
            roleAccessData.save();
        }
        await this.success(200, "授权成功");
    }
}
module.exports = RoleController;
